package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    //
    private String name;

    //注入Redis
    private StringRedisTemplate stringRedisTemplate;

    //定义每个用户的锁的key
    private static final String KEY_PREFIX="lock:";

    //生成UUID
    private  static  final String ID_PREFIX=UUID.randomUUID().toString(true)+"-";


    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //初始化指定脚本，避免多次io读取造成性能浪费
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    //利用静态代码块初始化
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        //指定lua脚本的读取位置
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //指定lua脚本的返回值
        UNLOCK_SCRIPT.setResultType(Long.class);
    }




    //创建锁
    @Override
    public Boolean tryLock(long timeOutSec) {

        //获取当前线程的id,利用UUID防止不同线程的id相同
        String id =ID_PREFIX+Thread.currentThread().getId();

        Boolean aBoolean = stringRedisTemplate
                .opsForValue()
                .setIfAbsent(KEY_PREFIX + name, id, timeOutSec, TimeUnit.SECONDS);

        //aBoolean是包装类要拆箱,防止aBoolean是null

        return Boolean.TRUE.equals(aBoolean);
    }

    @Override
    public void unlock() {

        //使用Lua脚本保证原子性
        //调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),//获取锁的标示
                ID_PREFIX+Thread.currentThread().getId()//获取当前线程标示
        );



    }


//    @Override
//    public void unlock() {
//
//        //判断线程的id是否是自己的
//        //获取线程标示
//        String threadId =ID_PREFIX+ Thread.currentThread().getId();
//
//        //获取锁中线程标示
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//
//        if(threadId.equals(id))
//        {
//            //释放锁，删除key即可
//            stringRedisTemplate.delete(KEY_PREFIX+name);
//        }
//
//
//    }
//


}
